<template>
    <div>
        <div class="title mb-8">
            <div class="text-6">停车记录管理</div>
        </div>
        <div class="query">
            <el-form :inline="true" :model="queryForm" class="demo-form-inline">
                <!-- <el-form-item label="车牌号">
                    <el-input
                        v-model="queryForm.carNum"
                        placeholder="请输入车牌号"
                    ></el-input>
                </el-form-item>
                <el-form-item label="停车场名称">
                    <el-input
                        v-model="queryForm.parkName"
                        placeholder="请输入停车场名称"
                    ></el-input>
                </el-form-item>
                <el-form-item label="支付状态">
                    <el-select
                        v-model="queryForm.payStatus"
                        placeholder="请选择"
                    >
                        <el-option label="全部" value="" />
                        <el-option label="未支付" value="0" />
                        <el-option label="已支付" value="1" />
                    </el-select>
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" icon="search" @click="getData"
                        >刷新</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <div class="actions mb-4">
            <el-button
                icon="plus"
                type="warning"
                @click="addDialogVisible = true"
                >添加</el-button
            >
        </div>
        <div class="data mb-4">
            <el-table :data="tableData" class="w-full" bpayRecord>
                <el-table-column prop="id" label="id" />
                <el-table-column prop="carNum" label="车牌号" />
                <el-table-column prop="parkName" label="停车场名称" />
                <el-table-column prop="enterTime" label="进入时间">
                    <template #default="scope">
                        {{ dateFromat(scope.row.enterTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="leaveTime" label="离开时间">
                    <template #default="scope">
                        {{ dateFromat(scope.row.leaveTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="parkSpaceType" label="车位类型">
                    <template #default="scope">
                        <el-tag v-if="scope.row.parkSpaceType === 0" type="info"
                            >自由车位</el-tag
                        >
                        <el-tag v-if="scope.row.parkSpaceType === 1"
                            >固定车位</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column prop="payRecordAmount" label="总费用" />
                <el-table-column prop="payRecordStatus" label="支付状态" >
                    <template #default="scope">
                        <el-tag v-if="scope.row.payRecordStatus === 0" type="danger"
                            >未支付</el-tag
                        >
                        <el-tag
                            v-else-if="scope.row.payRecordStatus === 1"
                            type="success"
                            >已支付</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column prop="payRecordNum" label="订单号" />

                <el-table-column label="操作" width="300">
                    <template #default="scope">
                        <el-space>
                            <el-button
                                :disabled="!!scope.row.payRecordStatus || scope.row.parkSpaceType === 1"
                                type="success"
                                icon="FullScreen"
                                @click="handleEdit(scope.row)"
                                >支付</el-button
                            >
                            <!-- <el-button
                                type="primary"
                                icon="edit"
                                @click="handleEdit(scope.row)"
                                >编辑</el-button
                            > -->
                            <el-button
                                type="danger"
                                icon="delete"
                                @click="handleDelete(scope.row.id)"
                                >删除</el-button
                            >
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                background
                layout="total, prev, pager, next"
                :total="total"
                :page-size="10"
                @current-change="getData"
                v-model:current-page="queryForm.page"
            />
        </div>
        <div class="add-dialog">
            <el-dialog
                title="添加停车记录"
                v-model="addDialogVisible"
                width="30%"
            >
                <el-form :model="addForm" label-position="top" ref="addFormRef">
                    <el-form-item label="车牌号" required prop="carId">
                        <el-select
                            v-model="addForm.carId"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入车牌号搜索车辆"
                            :remote-method="searchCarIdOptionList"
                        >
                            <el-option
                                v-for="item in carIdOptionList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="停车场" required prop="parkId">
                        <el-select
                            v-model="addForm.parkId"
                            placeholder="请选择停车场"
                        >
                            <el-option
                                v-for="item in parkOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="车位类型"
                        required
                        prop="parkSpaceType"
                    >
                        <el-select
                            v-model="addForm.parkSpaceType"
                            placeholder="请选择类型"
                        >
                            <el-option label="自由车位" :value="0" />
                            <el-option label="固定车位" :value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="进入时间" required prop="enterTime">
                        <el-date-picker
                            v-model="addForm.enterTime"
                            type="datetime"
                            placeholder="请选择进入时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="离开时间" prop="leaveTime">
                        <el-date-picker
                            v-model="addForm.leaveTime"
                            type="datetime"
                            placeholder="请选择离开时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        ></el-date-picker>
                    </el-form-item>

                    <el-form-item>
                        <el-button
                            type="primary"
                            icon="Check"
                            @click="addSubmit"
                            >提交</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-dialog>
            <PayModal ref="payRef" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { cloneDeep, keys, pick, pickBy } from 'lodash-es'
import { ref } from 'vue'
import { getParkOptionListApi } from '@/apis/park'
import {
    createParkRecordApi,
    deleteParkRecordApi,
    getParkRecordPageApi,
    updateParkRecordApi,
} from '@/apis/parkRecord'
import { getCarPageApi } from '@/apis/car'
import { dateFromat } from '@/utils/dateFormat'
import { getGenPayRecordApi } from '@/apis/payRecord'
import dayjs from 'dayjs'

const queryForm = ref({
    number: '',
    parkId: '',
    type: '',
    status: '',
    ownerId: '',
    page: 1,
})

// 添加表单
const addDialogVisible = ref(false)
const addFormRef = ref<any>(null)
// 添加表单数据
const defaultAddVal = {
    carId: undefined, // 车辆id
    parkId: undefined, // 停车场id
    enterTime: '', // 进入时间
    leaveTime: undefined, // 离开时间
    parkSpaceType: 0, // 0 自由车位 1 固定车位，表示这条记录产生的时候的车位类型
}
const addForm = ref(cloneDeep(defaultAddVal))
// 添加提交
const addSubmit = () => {
    addFormRef.value!.validate(async (valid) => {
        if (valid) {
            const res = await createParkRecordApi(addForm.value)
            if (res) {
                addDialogVisible.value = false
                ElMessage.success('成功')
                addForm.value = cloneDeep(defaultAddVal)
                getData()
            }
        } else {
            return false
        }
    })
}

const payRef = ref<any>(null)

// 点击支付
const handleEdit = async (row) => {
    const leaveTime = dayjs(row.leaveTime || Date.now()).format('YYYY-MM-DD HH:mm:ss').toString()
    const payRecord = await getGenPayRecordApi({
        parkId: row.parkId,
        parkSpaceType: row.parkSpaceType,
        enterTime: row.enterTime,
        leaveTime,
    }) as any
    // 付钱产生支付记录
    const payRes = await payRef.value.pay({
        amount: payRecord.price,
        realAmount: payRecord.price,
        method: '系统后台支付',
        type: 0,
        comment: `${row.carNum}停车费用`,
    })
    if (!payRes) return
    // 修改停车记录
    const updateRes = await updateParkRecordApi(row.id, {
        leaveTime,
        payRecordId: payRes.id,
    })
    if (updateRes) {
        ElMessage.success('完成')
        getData()
    }
}

// 删除
const handleDelete = (id) => {
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            await deleteParkRecordApi(id)
            ElMessage.success('删除成功!')
            getData()
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}

// 表格数据
const tableData = ref<any>([])
const total = ref(0)

// 计费模式下拉选项
const parkOptions = ref<any>([])

// 获取表格数据
const getData = async () => {
    const queryData = cloneDeep(queryForm.value)
    const query = pickBy(queryData, (item) => item !== '' && item !== null)
    const res = (await getParkRecordPageApi(query)) as any
    tableData.value = res.rows
    total.value = res.total
}

// 获取计费模式下拉选项
const getParkOptions = async () => {
    const res = (await getParkOptionListApi()) as any
    parkOptions.value = res
}

const getParkOptionById = (id) => {
    if (parkOptions.value.length === 0) {
        return {}
    }
    return parkOptions.value.find((item) => item.id === id)
}

getData()
getParkOptions()

const carIdOptionList = ref<any>([])

// 搜索车牌号
const searchCarIdOptionList = async (query) => {
    if (query === '') {
        carIdOptionList.value = []
        return
    }
    const res = (await getCarPageApi({
        carNum: query,
    })) as any
    carIdOptionList.value = res.rows.map((item) => ({
        id: item.id,
        name: item.carNum,
    }))
}
</script>

<style scoped></style>
